import { Init, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Equal } from 'typeorm';
import { DemandInfoEntity } from '../entity/info';

/**
 * 描述
 */
@Provide()
export class DemandInfoService extends BaseService {
  @InjectEntityModel(DemandInfoEntity)
  demandInfoEntity: Repository<DemandInfoEntity>;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.demandInfoEntity);
  }

  /**
   * 添加需求信息
   */
  async addDemand(params) {
    await this.demandInfoEntity.insert(params);
    return params;
  }

  async updateDemand(params) {
    const info = await this.getDemandById(params.uuid);
    if (!info) throw new CoolCommException('用户不存在');

    try {
      return await this.demandInfoEntity.update({ uuid: params.uuid }, params);
    } catch (err) {
      throw new CoolCommException('更新失败，参数错误');
    }
  }

  async getDemandByUserId(userId) {
    const info = await this.demandInfoEntity.find({
      where: { userId: Equal(userId) },
      order: { updateTime: 'DESC' },
    });
    return info;
  }
  async getDemandById(uuid) {
    const info = await this.demandInfoEntity.findOneBy({ uuid: Equal(uuid) });
    return info;
  }
}
